<template>
  <div>
    <i class="el-icon-circle-plus-outline" @click="dialogFormVisible=true"></i>
    <el-dialog
      title="添加论文/修改论文数据"
      :visible.sync="dialogFormVisible"
      @open="init"
      @close="clear"
      ref="dialog"
      width="30%">
      <el-form v-model="form"
               style="text-align: left"
               ref="paperForm"
               :model="form"
               :rules="rules"
               label-width="80px">
        <el-form-item label="论文名" prop="title">
          <el-input v-model="form.title"
                    auto-complete="off"
                    style="caret-color: black; " placeholder="无需添加《》"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
            <el-select
              v-model="form.author"
              placeholder="依此使用回车键入作者的名字"
              filterable
              multiple
              allow-create
              style="width: 100%;caret-color:black"
              :popper-append-to-body="false"
              default-first-option
              ref="authorSelect">
            </el-select>
        </el-form-item>
        <el-form-item label="发表会议" prop="conference">
          <el-input v-model="form.conference" auto-complete="off" style="caret-color: black"
                    placeholder="请输入发表会议"></el-input>
        </el-form-item>
        <el-form-item label="发表日期" prop="releaseDate">
          <el-date-picker v-model="form.releaseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发布日期"
                          style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="论文类型" prop="type">
          <el-select v-model="form.type"
                     style="width: 100%"
                     placeholder="请选择论文类型">
            <el-option value="0" label="理论证明型"></el-option>
            <el-option value="1" label="综述型"></el-option>
            <el-option value="2" label="实验型"></el-option>
            <el-option value="3" label="⼯具型"></el-option>
            <el-option value="4" label="数据集型"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="论文链接" prop="paperLink">
          <el-input placeholder="请输入内容" v-model="form.paperLink" style="caret-color: black">
            <template slot="prepend">Https://</template>
          </el-input>
        </el-form-item>
        <el-form-item label="研究方向" prop="directions">
          <tree-select
            ref="treeSelect"
            :lazy="true"
            :props="props"
            :multiple="true"
            :collapse="true"
            :options="optionData"
            v-model="form.directions"
            :clearable="true"
            :accordion="false"
            :expandedNode="false"
            style="width: 100%"
            @getValue="getValue($event)"
            @load="loadNodes"
          ></tree-select>
        </el-form-item>
        <el-form-item prop="abstract" label="摘要">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入摘要"
            v-model="form.abstract"
            style="caret-color: black"
            resize="none"
          ></el-input>
        </el-form-item>
        <el-form-item prop="id" style="height: 0">
          <el-input type="hidden" v-model="form.paperId" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="id" style="height: 0">
          <el-input type="hidden" v-model="form.uploadDate" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="onSubmit('paperForm')">确定</el-button>
          <el-button @click="clear">取消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>

import TreeSelect from "../utils/TreeSelect";

export default {
  name: "EditForm",
  components: {TreeSelect},
  data() {
    //论文名校验
    var titleValidate = (rule, value, callback) => {
      if (value === '')
        callback(new Error('请输入论文名'))
      callback()
    };
    //作者校验
    var authorValidate = (rule, value, callback) => {
      if (value.length===0)
        callback(new Error('请输入至少一个作者名字'))
      callback()
    };
    //会议校验
    var conferenceValidate = (rule, value, callback) => {
      if (value === '')
        callback(new Error('请输入会议名称'))
      callback()
    };
    //日期校验
    var dateValidate = (rule, value, callback) => {
      if (value === '')
        callback(new Error('请选择论文发表日期'))
      callback()
    };
    //类型校验
    var typeValidate = (rule, value, callback) => {
      if (value === '')
        callback(new Error('请选择论文类型'))
      callback()
    };
    //URL校验
    var linkValidate = (rule, value, callback) => {
      if (value === '')
        callback(new Error('请输入论文链接地址'))
      callback()
    };
    //研究方向校验
    var directionValidate = (rule, value, callback) => {

      if (value==null||value.length===0)
        callback(new Error('请输入至少选择一个论文方向'))
      callback()
    };
    //摘要校验
    var abstractValidate = (rule, value, callback) => {
      if (value==='')
        callback(new Error('请输入摘要内容'))
      callback()
    };
    return {
      //表单属性
      dialogFormVisible: false,
      formLabWidth: '80px',
      form: {
        paperId: '',
        title: '',
        author: [],
        conference: '',
        releaseDate: '',
        type: '',
        abstract: '',
        paperLink: '',
        uploadDate:'',
        directions: []
      },
      /*
        表单的验证方式
       */
      rules: {
        title: [
          {
            validator: titleValidate, trigger: 'blur'
          },
        ],
        author: [
          {
            validator: authorValidate, trigger: 'blur'
          }
        ],
        conference:[
          {
            validator:conferenceValidate,trigger:'blur'
          }
        ],
        releaseDate:[
          {
            validator:dateValidate,trigger:'blur'
          }
        ],
        type:[
          {
            validator:typeValidate,trigger:'blur'
          }
        ],
        paperLink:[
          {
            validator:linkValidate,trigger:'blur'
          }
        ],
        directions:[
          {
            validator:directionValidate,trigger:'blur'
          }
        ],
        abstract:[
          {
            validator:abstractValidate,trigger:'blur'
          }
        ]
      },
      /*
        研究方向节点属性
       */
      props: {
        value: 'id',
        label: 'name',
        pid: 'parentId',
        children: 'children',
        isLeaf: 'leaf'
      },
      selectList: []
    }
  },
  methods: {
    /*
      开启
     */
    init(){
      // console.log(this.form.paperId)
      this.$nextTick(()=>{
        if(this.form.paperId!=null&&this.form.paperId!==''){
          this.$axios(`/paper/getDirections/paperId=${this.form.paperId}`).then(res=>{
            let arr=[]
            res.data.data.forEach(item=>{
              arr.push(item.directionId)
            })
            this.form.directions=arr
            this.$refs.treeSelect.setCheckedKeys(arr)
          }).catch(failRes=>{
            console.log(failRes)
          })
        }
      })
    },
    /*
      清空
     */
    clear() {
      this.$refs.treeSelect.clearHandle()
      this.form = {
        paperId:'',
        title: '',
        author: [],
        conference: '',
        releaseDate: '',
        type: '',
        abstract: '',
        paperLink: '',
        directions: [],
      }
      this.dialogFormVisible= false
    },
    /*
      提交
     */
    onSubmit(formName) {
      var author=this.form.author.join(' ')
      var directionId=JSON.parse(JSON.stringify(this.form.directions))

      if(this.form.paperId==='') {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post('/paper/upload', {
              title: this.form.title,
              author: author,
              conference: this.form.conference,
              releaseDate: this.form.releaseDate,
              type: this.form.type,
              paperLink: this.form.paperLink,
              directionId: directionId,
              id: this.$store.state.id,
              uploadDate: this.currentDate(),
              paperAbstract: this.form.abstract
            }).then(() => {
              this.dialogFormVisible = false
              this.$emit('onSubmit')
            }).catch(() => {

            })
          } else {
            return false
          }
        })
      }
      else{
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post('/paper/update', {
              paperId:this.form.paperId,
              title: this.form.title,
              author: author,
              conference: this.form.conference,
              releaseDate: this.form.releaseDate,
              type: this.form.type,
              paperLink: this.form.paperLink,
              directionId: directionId,
              id: this.$store.state.id,
              uploadDate: this.form.uploadDate,
              paperAbstract: this.form.abstract
            }).then(() => {
              this.dialogFormVisible = false
              this.$emit('onSubmit')
            }).catch(() => {

            })
          } else {
            return false
          }
        })
      }

    },

    /*
    加载时间
     */
    currentDate() {
      let d = new Date();
      let year = d.getFullYear();
      let month = d.getMonth();
      month = month + 1 > 12 ? 1 : month + 1;
      month = month > 9 ? month : "0" + month.toString();
      let day = d.getDate();
      day=day>9?day:"0"+day.toString();
      let hour = d.getHours();
      hour = hour > 9 ? hour : "0" + hour.toString();
      let minute = d.getMinutes();
      minute = minute > 9 ? minute : "0" + minute.toString();
      let second = d.getSeconds();
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    /*
    懒加载节点
     */
    loadNodes(node, resolve) {
      let self = this
      let treeData = []
      if (node.level === 0) {
        self.$axios.get(`/direction/getChildren/0`).then(res => {
          res.data.data.forEach(e => {
            e.id = e.directionId
            treeData.push(e)
          })
          resolve(treeData)
        }).catch(() => {
          resolve([])
        })
      } else {
        self.$axios.get(`/direction/getChildren/${node.data.id}`).then(res => {
          res.data.data.forEach(e => {
            e.id = e.directionId
            treeData.push(e)
          })
          resolve(treeData)
        }).catch(() => {
          resolve([])
        })
      }
    },
    /*
      设置值
     */
    getValue(value){
      this.form.directions=value
    },

  },
  computed: {
    /*
      遍历selectList的所有选项，然后将所有的子元素挂载在父元素之下，
      然后返回前一层
     */
    optionData() {
      let cloneData = JSON.parse(JSON.stringify(this.selectList))
      return cloneData.filter(father => {
        let branchArr = cloneData.filter(child => father.id === child.parentId); // 返回每一项的子级数组
        branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
        return father.parentId === 0; //返回第一层
      })
    }
  },
  mounted() {
    //让对话框预加载
    this.$refs.dialog.rendered=true
  }
}
</script>

<style scoped>
.el-icon-circle-plus-outline {
  margin: -20px 0 0 20px;
  font-size: 20px;
  float: right;
  caret-color: transparent;
}

div, span {
  caret-color: transparent;
}

/*
  隐藏右侧下拉表单箭头
 */
/deep/ .el-select .el-input .el-select__caret {
  display: none !important;
}

/*
  隐藏下拉表单
*/
/deep/ .el-select-dropdown {
  display: none !important;
}


</style>
